package me.zhengjie.config.mica.mqtt.listener;

import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
import net.dreamlu.iot.mqtt.core.server.model.Message;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.tio.core.ChannelContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wsq
 */
@Service
public class MqttServerMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(MqttServerMessageListener.class);
    @Autowired
    private MqttServerTemplate mqttServerTemplate;
    @Autowired
    MagicAPIService service;

    @EventListener
    public void onMessage(Message message) {
        String clientId = message.getFromClientId();
        ChannelContext context = mqttServerTemplate.getChannelContext(clientId);

        logger.info("context:{} clientId:{} message:{} payload:{}", context, clientId, message, ByteBufferUtil.toString(message.getPayload()));

        Map<String, Object> params = new HashMap<>();
        params.put("clientId",clientId);

        params.put("topic",message.getTopic());
        params.put("payload",ByteBufferUtil.toString(message.getPayload()));
        params.put("message",message);
        Object result = service.execute("POST", "/interface/callback/mqtt_message", params);


        logger.info("callback result:{} ", result.toString());

    }

}
